package com.itheima.socketWork01;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class ServerUdp {
    public static void main(String[] args) throws IOException {
    //1、创建DatagramSocket对象，指定接收的端口号
        DatagramSocket ds = new DatagramSocket(10086);
    //2、接收端要一直接收数据，所以定义死循环
        while (true){
    //3、创建一个数据包DatagramPacket，用于接收数据
            byte[] bytes =new byte[1024];
            DatagramPacket dp=new DatagramPacket(bytes,bytes.length);
    //4、使用DatagramSocket对象接收数据
            ds.receive(dp);
    //5、解析数据包，获取数据包中的字节数据，和字节数据的有效长度
            InetAddress in = dp.getAddress();
            String host = in.getHostAddress();


            byte[] data = dp.getData();
            int length = dp.getLength();

            System.out.println(new String(bytes,0,bytes.length));
          String datas = new String(data,0,length);
            System.out.println(host+"说:"+datas);


        }
//6、根据DatagramSocket对象获取发送者ip

//7、将数据信息解码成字符串，和发送者ip信息一起在控制台打印
    }
}
